'''
Created on Dec 5, 2009

@author: tliu
'''

from google.appengine.ext import db
from error import ProjectError
from Subscription import Subscription 

def getProjectByName(name):
    projects = Project.all()
    matches = filter(lambda x:x.name == name, projects)
    if len(matches) < 1:
        raise ProjectError.ProjectError("No such project!")
    
    return matches[0]

def createProject(name, owner, desc):
    if Project.get_by_key_name(name) != None:
        raise ProjectError.ProjectError("Duplicate project name!")
    project = Project(name = name,
                      owner = owner,
                      desc = desc,
                      url = "http://cs440x-bookbook.appspot.com/project/",
                      key_name = name)
    project.entries = []
    project.put()
    return project
    
class Project(Subscription):
    from User import User
    owner = db.ReferenceProperty(User, required=True)
    name = db.StringProperty(required=True)
    desc = db.TextProperty(required=True)
    entries = db.ListProperty(db.Key)
    url = db.LinkProperty(required=True)
    
    def updateDesc(self, desc):
        self.desc = desc
        self.put()
        
    def addEntry(self, entry):
        self.entries.append(entry.key())
        self.put()
        
    def getEntries(self):
        from Entry import Entry
        return map(lambda x:Entry.get(x), self.entries)
    
    def getItems(self):
        item_list = []
        for entry in self.getEntries():
            item_list.append({"title" : "%s: %s" % (self.project_ref.name, entry.title),
                              "date" : entry.date,
                              "content" : entry.content,
                              "author" : entry.author.name,
                              "url" : self.url,
                              "footer" : "Comments: %d" % len(entry.comments)}) 
        return item_list

